package com.sys.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sys.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 阿里云OSS文件上传工具类
 */
@Slf4j
@Component
public class OssUtil {

    @Autowired
    private OssConfig ossConfig;

    /**
     * 上传文件到OSS
     *
     * @param file   要上传的文件
     * @param userId 用户ID，用于构建文件路径
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    public String uploadFile(MultipartFile file, Long userId) throws IOException {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            originalFilename = "unknown";
        }

        // 获取文件扩展名
        String fileExtension = "";
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex > 0) {
            fileExtension = originalFilename.substring(dotIndex);
        }

        // 构建文件存储路径：task-photos/user_{userId}/yyyyMMdd/uuid.ext
        String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = UUID.randomUUID().toString().replace("-", "") + fileExtension;
        String objectName = ossConfig.getPrefix() + "user_" + userId + "/" + datePath + "/" + fileName;

        OSS ossClient = null;
        try {
            // 创建OSS客户端实例
            ossClient = new OSSClientBuilder().build(
                    ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret()
            );

            // 上传文件流
            InputStream inputStream = file.getInputStream();
            
            // 创建并设置文件元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentDisposition("inline");
            metadata.setContentLength(file.getSize());
            
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucketName(),
                    objectName,
                    inputStream,
                    metadata
            );

            // 执行上传
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("文件上传成功到OSS: {}", objectName);

            // 返回文件访问URL
            String fileUrl = ossConfig.getDomain() + "/" + objectName;
            return fileUrl;

        } catch (Exception e) {
            log.error("文件上传到OSS失败: {}", e.getMessage(), e);
            throw new IOException("文件上传失败: " + e.getMessage(), e);
        } finally {
            // 关闭OSS客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 删除OSS上的文件
     *
     * @param fileUrl 文件URL
     */
    public void deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return;
        }

        // 从URL中提取objectName
        String objectName = extractObjectName(fileUrl);
        if (objectName == null) {
            log.warn("无法从URL中提取objectName: {}", fileUrl);
            return;
        }

        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(
                    ossConfig.getEndpoint(),
                    ossConfig.getAccessKeyId(),
                    ossConfig.getAccessKeySecret()
            );

            ossClient.deleteObject(ossConfig.getBucketName(), objectName);
            log.info("文件删除成功: {}", objectName);

        } catch (Exception e) {
            log.error("删除OSS文件失败: {}", e.getMessage(), e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 从完整URL中提取objectName
     *
     * @param fileUrl 文件完整URL
     * @return objectName
     */
    private String extractObjectName(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return null;
        }

        // 如果URL包含域名，去掉域名部分
        String domain = ossConfig.getDomain();
        if (fileUrl.startsWith(domain)) {
            String objectName = fileUrl.substring(domain.length());
            // 去掉开头的斜杠
            if (objectName.startsWith("/")) {
                objectName = objectName.substring(1);
            }
            return objectName;
        }

        // 如果URL包含endpoint，去掉endpoint部分
        String endpoint = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint();
        if (fileUrl.startsWith(endpoint)) {
            String objectName = fileUrl.substring(endpoint.length());
            if (objectName.startsWith("/")) {
                objectName = objectName.substring(1);
            }
            return objectName;
        }

        // 否则认为整个URL就是objectName
        return fileUrl;
    }
}

